<script setup>
import { ref, onMounted } from 'vue'

const props = defineProps({
  width: {
    type: Number,
    default: 700
  },
  height: {
    type: Number,
    default: 420
  },
  data: {
    type: Array,
    default: () => []
  }
})
const echart = ref(null)

// 示例数据
const chartData = ref(props.data)

// 处理数据，为每个类别创建两个柱子
const categories = chartData.value[0] || [] // 增加默认空数组避免报错
const tradeData = chartData.value[1] || []
const reserveData = chartData.value[2] || []

// 创建新的x轴数据
const xAxisData = []
for (let i = 0; i < categories.length; i++) {
  xAxisData.push(categories[i] + '-贸易')
  xAxisData.push(categories[i] + '-储备')
}

// 创建新的系列数据
const seriesData = []
for (let i = 0; i < categories.length; i++) {
  seriesData.push(props.data[1][i] || 0)
  seriesData.push(props.data[2][i] || 0)
}
// 最大值数据
const MAX = 50

const option = {
  backgroundColor: 'transparent',
  legend: {
    tooltip: {
      show: true
    },
    data: ['储备粮', '贸易粮'],
    top: '0%',
    right: '8%',
    icon: 'circle',
    itemWidth: 11,
    itemHeight: 11,
    textStyle: {
      color: '#fff',
      fontSize: '16rem'
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: function (params) {
      console.log(params)
      const dataIndex = params[0].dataIndex
      const categoryIndex = Math.floor(dataIndex / 2)
      const category = categories[categoryIndex] || ''
      const type = dataIndex % 2 === 0 ? '储备粮' : '贸易粮'
      return `${category} - ${type}: ${params[1].value}吨`
    }
  },
  graphic: [
    {
      type: 'text',
      left: '5%',
      top: '5%',
      style: {
        text: '单位：吨',
        fontSize: '16rem',
        fill: 'rgba(0, 209, 229, 1)',
        fontFamily: 'Arial'
      }
    }
  ],
  grid: {
    left: '5%',
    right: '10%',
    bottom: '20%', // 进一步增加底部边距，确保文字不被截断
    top: '15%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: xAxisData,
    axisLine: {
      show: false,
      lineStyle: {
        color: 'white' // 确保轴线可见，作为参考
      }
    },
    offset: 5,
    axisTick: {
      show: false, // 隐藏刻度线
      length: 9,
      alignWithLabel: true,
      lineStyle: {
        color: '#7DFFFD'
      }
    },
    axisLabel: {
      show: true, // 强制显示文字
      fontSize: '16rem', // 增大字体，更容易看清
      color: 'rgba(0, 209, 229, 1)', // 确保颜色与背景有对比度
      // 修正标签显示逻辑：每组第二个位置（储备粮右侧）显示类别名称
      formatter: function (value, index) {
        // 取原始类别名称（去掉-贸易/-储备后缀）
        const categoryName = value.split('-')[0]
        // 每两个数据显示一次标签（在储备粮位置的右侧，即两根柱子中间）
        if (index % 2 === 1) {
          return categoryName
        }
        return ''
      },
      padding: [0, 0, 0, -30],
      // 修改文字偏移量

      interval: 0, // 强制显示所有标签，不自动隐藏
      margin: 5, // 增加与轴线的距离
      rotate: 0 // 不旋转文字，确保清晰
    }
  },
  yAxis: {
    min: 0,
    max: MAX,
    type: 'value',
    axisLine: {
      show: false,
      lineStyle: {
        color: 'white'
      }
    },
    splitLine: {
      show: true,
      lineStyle: {
        type: 'dashed',
        color: 'rgba(255,255,255,0.1)'
      }
    },
    axisTick: {
      show: false
    },
    axisLabel: {
      show: true,
      color: 'rgba(0, 209, 229, 1)',
      fontSize: '16rem'
    },
    boundaryGap: ['20%', '20%']
  },
  series: [
    // 背景参考柱（最大值）
    {
      type: 'custom',
      renderItem: function (params, api) {
        const categoryIndex = Math.floor(params.dataIndex / 2)
        // 调整偏移量使两根柱子靠近
        const offset = params.dataIndex % 2 === 0 ? -0.15 : 0.15
        const centerX = api.coord([api.value(0) + offset, 0])[0]

        const leftOffset = 9
        const rightOffset = 13
        const left = centerX - leftOffset
        const right = centerX + rightOffset

        const yTop = api.coord([api.value(0), api.value(1)])[1]
        const yBottom = api.coord([api.value(0), 0])[1]

        return {
          type: 'rect',
          shape: {
            x: left,
            y: yTop,
            width: right - left,
            height: yBottom - yTop
          },
          style: {
            fill: 'rgba(0, 126, 255, .2)'
          }
        }
      },
      data: new Array(xAxisData.length).fill(MAX),
      silent: true
    },
    // 贸易粮数据
    {
      type: 'custom',
      name: '储备粮',
      itemStyle: {
        // legend颜色单独设置 不会从renderItem中继承
        color: 'rgba(0, 126, 255, 1)' // 与渐变主色一致（蓝色），用于图例显示
      },
      renderItem: (params, api) => {
        if (params.dataIndex % 2 !== 0) {
          return
        }

        // 调整贸易粮柱子位置
        const baseValue = api.value(0)
        const offsetValue = baseValue - 0.15
        const location = api.coord([offsetValue, api.value(1)])

        const color = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(8, 53, 122, 1)' },
          { offset: 0.9, color: 'rgba(55, 178, 244, 1)' }
        ])

        return {
          type: 'group',
          children: [
            {
              type: 'CubeLeft',
              shape: {
                api,
                xValue: offsetValue,
                yValue: api.value(1),
                x: location[0],
                y: location[1],
                xAxisPoint: api.coord([offsetValue, 0])
              },
              style: {
                fill: color
              }
            },
            {
              type: 'CubeRight',
              shape: {
                api,
                xValue: offsetValue,
                yValue: api.value(1),
                x: location[0],
                y: location[1],
                xAxisPoint: api.coord([offsetValue, 0])
              },
              style: {
                fill: color
              }
            },
            {
              type: 'CubeTop',
              shape: {
                api,
                xValue: offsetValue,
                yValue: api.value(1),
                x: location[0],
                y: location[1],
                xAxisPoint: api.coord([offsetValue, 0])
              },
              style: {
                fill: color
              }
            }
          ]
        }
      },
      data: seriesData
    },
    // 储备粮数据
    {
      type: 'custom',
      name: '贸易粮',
      itemStyle: {
        // legend颜色单独设置 不会从renderItem中继承
        color: 'rgba(251, 179, 8, 1)' // 与渐变主色一致（蓝色），用于图例显示
      },
      // 本质上还是渲染的两种颜色为一根柱子渲染了 n根 只是按需显示了 n/2根 上面同理
      renderItem: (params, api) => {
        if (params.dataIndex % 2 !== 1) {
          return
        }

        // 调整储备粮柱子位置
        const baseValue = api.value(0)
        const offsetValue = baseValue + 0.15
        const location = api.coord([offsetValue, api.value(1)])

        const color = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(251, 179, 8, 1)' },
          { offset: 0.5, color: 'rgba(151, 135, 22, 1)' }
        ])

        return {
          type: 'group',
          children: [
            {
              type: 'CubeLeft',
              shape: {
                api,
                xValue: offsetValue,
                yValue: api.value(1),
                x: location[0],
                y: location[1],
                xAxisPoint: api.coord([offsetValue, 0])
              },
              style: {
                fill: color
              }
            },
            {
              type: 'CubeRight',
              shape: {
                api,
                xValue: offsetValue,
                yValue: api.value(1),
                x: location[0],
                y: location[1],
                xAxisPoint: api.coord([offsetValue, 0])
              },
              style: {
                fill: color
              }
            },
            {
              type: 'CubeTop',
              shape: {
                api,
                xValue: offsetValue,
                yValue: api.value(1),
                x: location[0],
                y: location[1],
                xAxisPoint: api.coord([offsetValue, 0])
              },
              style: {
                fill: color
              }
            }
          ]
        }
      },
      data: seriesData
    }
  ]
}

const echart2 = ref()

onMounted(() => {
  if (echart2.value) {
    const e = echarts.init(echart2.value)
    e.setOption(option)

    // 监听窗口大小变化，防止文字被截断
    window.addEventListener('resize', () => {
      e.resize()
    })
  }
})
</script>

<template>
  <div
    ref="echart2"
    :style="{
      width: width + 'rem',
      height: height + 'rem'
    }"
  ></div>
</template>
